<?php

require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/appconf.php');
require_once(dirname(dirname(__FILE__)).'/config.php');
class mapi_itrial_product extends Site {

    function setup() {
        $this->run_modes('list', 'get_user_action');
        $this->start_mode('list');
        parent::setup();
    }

    function cgiapp_prerun() {
        $this->Product = getModel('Model_Product');
        $this->height = 300;
        $this->width = 300;
        $this->mapi_object = getModel('MAPI_Base');
        parent::cgiapp_prerun();
    }

    function action_list() {
        $page = intval($this->get_q('page', 1, 'int'));
        $id = intval($this->get_q('id', 0, 'int'));

        $sub_category = intval($this->get_q('sub_category', 0, 'int'));
        $category_topid = intval($this->get_q('category', 0, 'int'));
        $keyword = $this->get_q('keyword');
        $pagesize = intval($this->get_q('pagesize', 10, 'int'));
        $type = intval($this->get_q('type', 6, 'int')); //1 正在邀請試用/體驗中的和coming ，3已錯過邀請時間，6開始提交報告後，並且報告數大於1的，0是全部

        if ($type == 1 || $type == 7) {
            $pagesize = 99;
        }
        $url = $this->param('URL');
        $www = $this->param('WWW');
        $kvcobj = getCache('mapi_product_list', array('expire' => KVC_EXPIRE));
        $product_list = $kvcobj->get('mapi_product_list' . $category_topid . "_" . $sub_category . "_" . $page . "_" . $keyword . "_" . $pagesize . "_" . $type . "_" . $id . "_");
        if (!$product_list) {

            $a_result = $this->get_product_list($type, $page, $pagesize, $category_topid, $sub_category, $id, $keyword, $url, $www);

            $product_list['result'] = $a_result['result'];
            $product_list['pageinfo'] = $a_result['pageinfo'];
            $a_result_7 = array();
            if ($type == 1) {
                $a_result_7 = $this->get_product_list(7, $page, $pagesize, $category_topid, $sub_category, $id, $keyword, $url, $www);
                //echo '<pre>' . var_export($a_result_7, 1) . '</pre>';

                $product_list['result'] = array_merge($a_result['result'], $a_result_7['result']);
                $product_list['pageinfo'] = array(
                    'total' => count($product_list['result']),
                    'pagecount' => 1,
                    'pagesize' => 99,
                    'curpage' => 1
                );
            }

            $kvcobj->set('mapi_product_list' . $category_topid . "_" . $sub_category . "_" . $page . "_" . $keyword . "_" . $pagesize . "_" . $type . "_" . $id . "_", $product_list);
        }

        return $this->mapi_object->to_json($product_list['result'], $product_list['pageinfo']);
    }

    function get_product_list($type, $page, $pagesize, $category_topid, $sub_category, $id, $keyword, $url, $www) {
        $dateArr = array(1 => '天', 2 => '小時', 3 => '分鐘', 4 => '秒');
        $h_param = array(
            'member_type' => 0,
            'type' => $type,
            'page' => $page,
            'size' => $pagesize,
            'scores' => ($type == 6) ? 1 : 0,
            'category' => $category_topid,
            'category_id' => $sub_category,
            'keyword' => $keyword,
            'is_mobile' => 0,
            'pid' => $id ? $id : 0,
        );
        $product_list = $this->Product->h_get_product_list($h_param);

        #评分项目
        $param = array();
        $param['field'] = "id,cname";
        $param['where'] = "status=1";
        $param['order'] = "id asc"; //"id asc"
        $param['group'] = "";
        $param['limit'] = "";
        $param['pagesize'] = "";
        $param['page'] = "";
        $param['join'] = "";
        $param['on'] = "";
        $vote_option_data = db_query_hash('product_vote_option', $param);
        $vote_option_arr = array();
        if ($vote_option_data['result']) {
            foreach ($vote_option_data['result'] as $value) {
                $vote_option_arr[$value['id']] = $value['cname'];
            }
        }


        $a_result = array();

        $a_required_field = array('id', 'points', 'apply_endtime', 'apply_starttime', 'report_starttime', 'report_endtime', 'name', 'cname', 'brand', 'member_type', 'quota', 'apply_num', 'click', 'likes', 'body', 'price', 'capacity_trial', 'category', 'attribute_label1', 'attribute_value1', 'attribute_label2', 'attribute_value2', 'attribute_label3', 'attribute_value3', 'attribute_label4', 'attribute_value4', 'attribute_label5', 'attribute_value5', 'attribute_label6', 'attribute_value6', 'attribute_label7', 'attribute_value7', 'attribute_label8', 'attribute_value8', 'is_live', 'is_trial', 'status', 'well', 'category_score_num', 'category_score1', 'category_score2', 'category_score3', 'category_score4', 'category_score5', 'category_score6', 'category_score7', 'category_score8', 'well_score_num1', 'well_score_num2', 'well_score_num3', 'well_score_num4', 'well_score_num5', 'agegroup1', 'agegroup2', 'agegroup3', 'agegroup4', 'agegroup5', 'agegroup6', 'reports', 'vote_option', 'min_pic_num', 'max_pic_num', 'trial_terms');
        $a_n_attrubute = array('attribute_value1', 'attribute_value2', 'attribute_value3', 'attribute_value4', 'attribute_value5', 'attribute_value6', 'attribute_value7', 'attribute_value8');

        if ($product_list['result']) {
            $n_attrubute = 0;
            foreach ($product_list['result'] as $value) {

                $h_row = array();
                foreach ($a_required_field as $field) {
                    $h_row['product'][$field] = $value[$field];
                }
                $n_attrubute = 0;
                foreach ($a_n_attrubute as $value_n_attrubute) {
                    if ($value[$value_n_attrubute])
                        $n_attrubute+=1;
                }

                #縮略圖
                //$h_row['cover_url'] = $url . showphoto($www . $value['cover'], $this->width, $this->height);
                $h_row['product']['cover_url'] = photoResize($value['cover'], '800_800');
                #分數
                $h_row['product']['scores'] = $value['scores'] ? $value['scores'] : 0;

                $h_row['product']['category'] = (intval($h_row['product']['category'])) ? $h_row['product']['category'] : 0;

                #子分類
                $h_row['product']['sub_category'] = $value['product_layout_category'] ? $value['product_layout_category'] : 0;
                #屬性數量
                $h_row['product']['n_attrubute'] = $n_attrubute;
                $h_row['product']['lastmodify'] = strtotime($value['lastmodify']);
                $h_row['product']['share_url'] = $this->param('URL') . "r/p-" . $h_row['product']['id'];

                #圖片數量最少和最多默認值
                $h_row['product']['min_pic_num'] = !empty($h_row['product']['min_pic_num']) ? $h_row['product']['min_pic_num'] : ($h_row['product']['member_type'] == 5 ? 5 : 3);
                $h_row['product']['max_pic_num'] = !empty($h_row['product']['max_pic_num']) ? $h_row['product']['max_pic_num'] : ($h_row['product']['member_type'] == 5 ? 10 : 6);
                #評分項目名稱
                $a_vote_option = array();
                if ($h_row['product']['vote_option']) {
                    $vote_option_array = explode(",", $h_row['product']['vote_option']);
                    if ($vote_option_array) {
                        foreach ($vote_option_array as $value_option_array) {
                            $a_vote_option[] = $vote_option_arr[$value_option_array];
                        }
                    }
                }
                $h_row['product']['vote_option_array'] = $a_vote_option;
                $h_row['product']['vote_option_name'] = implode(",", $a_vote_option);
                $h_row['product']['brand_name'] = $value['type_name'];
                $date_time = explode(" ", str_diff_time($value['apply_endtime']));
                if (empty($date_time[0])) {
                    $str_date = '已經完結';
                } else {
                    $str_date = '尚餘' . $date_time[0] . $dateArr[$date_time[1]];
                }

                $trial_name = ($h_row['product']['member_type'] == 5) ? "體驗" : "試用";
                $_diff_day = (int) ((strtotime($value['report_endtime']) - strtotime($value['apply_starttime'])) / 86400);
                $capacity_trial = (!empty($value['capacity_trial'])) ? $trial_name . "規格：" . $value['capacity_trial'] : "";

                $message = "
                    編輯短評：" . $h_row['body'] . "
                    " . $trial_name . "期間 ：" . date('Y-m-d', strtotime($value['report_starttime'])) . " ~ " . date('Y-m-d', strtotime($value['report_endtime'])) . "
                    體驗日數 ：$_diff_day 日
                    名額 ：" . $value['quota'] . "
                    " . $capacity_trial;
                $button_array = array();

                if ($value['reports'] > 0 && $type==6) {
                    $button_array[] = array(
                        'text' => '查看報告',
                        'description' => "",
                        'color' => '0,0,255',
                        'action' => 'view_product_reports',
                        'type' => 'local'
                    );
                    $button_array[] = array(
                        'text' => '評分詳情',
                        'description' => "",
                        'color' => '0,0,255',
                        'action' => 'view_product_summary',
                        'type' => 'local'
                    );
                } else {
                    $button_array[] = array(
                        'text' => '查看申請',
                        'description' => "",
                        'color' => '0,0,255',
                        'action' => 'apply_reason',
                        'type' => 'local'
                    );
                }

                #狀態
                if (strtotime($value['apply_starttime']) > time()) {
                    $status_type = 1; //未到申請時間	coming soon	立即申請（不可click）
                    // $h_row['bgcolor'] = '255,0,0';
                    // $h_row['note'] = 'coming soon';
                    $status = 'coming soon';
                    $status_photo_url = MAPIURL."images/coming.png";
                    $photo_url = MAPIURL."images/remote_photo.png";
                } elseif (strtotime($value['apply_starttime']) <= time() && time() <= strtotime($value['apply_endtime'])) {
                    $status_type = 2; //已到申請時間	尚餘xx天	立即申請（可click）	check login，之後去產品頁（有申請按鈕）
                    // $h_row['bgcolor'] = '0,255,0';
                    // $h_row['note'] = '在可申請時間之內';
                    $status = $str_date;
                    $photo_url = MAPIURL."images/remote_photo.png";
                    $status_photo_url = MAPIURL."images/applied.png";
                    $button_array[] = array(
                        'text' => '立即申請',
                        'description' => "",
                        'color' => '0,255,0',
                        'action' => 'apply',
                        'type' => 'local'
                    );
                } elseif (strtotime($value['apply_endtime']) < time()) {
                    $status_type = 3; //已過申請時間	已完結	查看報告（可click）	click去報告頁	因為有可能沒有可申請的產品，不想list空，會出一定數量的過往申請
                    // $h_row['bgcolor'] = '0,0,255';
                    // $h_row['note'] = '已過申請時間，有或無報告都可以';
                    $status = $str_date;
                    $photo_url = MAPIURL."images/remote_photo.png";
                    $status_photo_url = MAPIURL."images/finish.png";
                }

                $h_row['user_action'] = array(
                    'button' => $button_array,
                    'remark' => '',
                    'message' => $message,
                    'debug_tag' => 'application_1',
                    'photo_url' => $photo_url
                );
                $h_row['application']=array(
                    'status'=>$status,
                    'bgcolor' => '0,255,0',
                    'status_type'=>$status_type,
                    'status_photo_url'=>$status_photo_url
                );

                $a_result[] = $h_row;
            }
        }

        return array('result' => $a_result, 'pageinfo' => $product_list['pageinfo']);
    }

    function action_get_user_action() {
        $mid = intval($this->get_q('mid', 0, 'int'));
        $pid = intval($this->get_q('pid', 0, 'int'));
        $token = $this->get_q('token', '');

        if (!$token || !$mid) {
            return $this->mapi_object->to_json(array(), array(), 0, "mid或token為空");
        }
        $product = $this->Product->get_product_byid($pid);
        if (empty($product)) {
            return $this->mapi_object->to_json(array(), array(), 0, "產品狀態錯誤");
        }

        if (strtotime($product['apply_starttime']) > time() || time() > strtotime($product['apply_endtime'])) {
            return $this->mapi_object->to_json(array(), array(), 0, "產品未開始或已經結束申請");
        }

        $is_apply = 0;
        if ($mid) {
            $p_application_num = db_query_count('product_application', "oid=" . mysql_escape_string($pid) . " and mid=" . mysql_escape_string($mid) . " and  status=1");
            $is_apply = ($p_application_num > 0) ? 1 : 0;
        }
        $botton_array = array();
        $botton_array[1] = array(
            array(
                'text' => '已經申請',
                'description' => 0, //1可以點擊，0不能點擊
                'color' => '255,0,0',
                'action' => 'nothing',
            )
        );
        $botton_array[0] = array(
            array(
                'text' => '立即申請',
                'description' => "",
                'color' => '0,255,0',
                'action' => 'apply',
            )
        );

        return $this->mapi_object->to_json($botton_array[$is_apply]);
    }

}

header("Content-type: text/html; charset=utf-8");
$webapp = new mapi_itrial_product();
$webapp->run();
?>